<?php

namespace KyleWechat\Wechat;

use KyleWechat\App;

/**
 * @method authorize(array $options) 跳转授权
 * @method userinfo(string $openid, string $access_token, string $type = 'userinfo') 获取用户详细信息
 * @method jssdk(string $url, $access_token)
 */
class Wechat extends App
{
    public function content(string $layer): Wechat
    {
        return $this->getClass($layer);
    }

    public function getAccessToken($code)
    {
        $res = $this->app->config->httpClient
            ->get($this->app->config::API['wechat']['access_token'],[
                'appid'      => $this->app->config->getAppid(),
                'secret'     => $this->app->config->getSecret(),
                'code'       => $code,
                'grant_type' => 'authorization_code'
            ]);
        return json_decode($res,true);
    }

    public function getPublicAccessToken()
    {
        $res = $this->app->config->httpClient
            ->get($this->app->config::API['access_token'],[
                'appid'      => $this->app->config->getAppid(),
                'secret'     => $this->app->config->getSecret(),
                'grant_type' => 'client_credential'
            ]);
        return json_decode($res,true);
    }

    private function getClass(string $layer)
    {
        $configs = explode('.',$layer);
        $str = '';
        foreach ($configs as $config) {
            $config = ucfirst($config);
            $str .= "\\{$config}";
        }
        $class = "\\KyleWechat\\Wechat{$str}";
        return $this->app->make($class);
    }
}